# -*- encoding=utf8 -*-

__author__ = "code哥"
from airtest.core.api import *
import sys
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

dev = False

if dev:
    poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
    from airtest.cli.parser import cli_setup

    if not cli_setup():
        auto_setup(__file__, logdir=None, devices=[
            "Android://127.0.0.1:5037/M960BDPT226TA?cap_method=JAVACAP&&ori_method=ADBORI",
        ])
else:
    import timeout_decorator

    # M960BDPT226TA WIFI 10.0.0.26 48003
    argv1 = str(sys.argv[1])
    argv2 = str(sys.argv[2])
    argv3 = str(sys.argv[3])
    argv4 = str(sys.argv[4])

    if argv2 == 'USB':
        conn_info = 'Android://127.0.0.1:5037/{uuid}?cap_method=JAVACAP&&ori_method=ADBORI'.format(
            uuid=argv1)
        device = connect_device(conn_info)
    else:
        # WIFI模式
        conn_info = 'Android://127.0.0.1:5037/{clientIp}:{port}'.format(
            clientIp=argv3,
            port=argv4)
        print(conn_info)
        device = connect_device(conn_info)

    poco = AndroidUiautomationPoco(device, use_airtest_input=True, screenshot_each_action=False)

    logdir = "{path}/static/source_img/{fileName}/{devices}".format(
        path=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        fileName=str(os.path.abspath(__file__).split('/')[-1]).split('.py')[0],
        devices=argv1)
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    auto_setup(__file__,
               logdir=logdir,
               devices=[conn_info, ],
               project_root="{root}".format(root=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))


def start():
    if not dev:
        set_logdir(logdir)
        # set_current(str(sys.argv[1]))
    # 退到桌面
    home()
    stop_app('com.xiangkan.android')
    sleep(1)
    start_app('com.xiangkan.android')
    start_home()


def start_home():
    sleep(15)
    closeIv = poco(type="android.widget.ImageView", name="com.xiangkan.android:id/closeIv")
    if closeIv.exists():
        closeIv.click()
    iv_close = poco(type="android.widget.ImageView", name="com.xiangkan.android:id/iv_close")
    if iv_close.exists():
        iv_close.click()
    btn_close = poco(type="android.widget.ImageView", name="com.xiangkan.android:id/btn_close")
    if btn_close.exists():
        btn_close.click()
    refresh_layout = poco(type="android.widget.FrameLayout", name="com.xiangkan.android:id/refresh_layout")
    refresh_layout.swipe([0, 0.5])
    sleep(2)
    common_recycler_view = poco(type="androidx.recyclerview.widget.RecyclerView",
                                name="com.xiangkan.android:id/common_recycler_view")
    if common_recycler_view.exists():
        common_recycler_list = common_recycler_view.children()
        if len(common_recycler_list) > 0:
            for index in range(len(common_recycler_list)):
                if index <= 0:
                    continue
                item = common_recycler_list[index]
                tvInfo = item.offspring("com.xiangkan.android:id/tvInfo", textMatches=".*广告.*")
                if not tvInfo.exists():
                    item.click()
                    break

            while True:
                loop_body()


@timeout_decorator.timeout(120)
def loop_body():
    print('loop_body......')
    sleep(1.5)
    more_minute_btn = poco(type="android.widget.TextView", name="com.xiangkan.android:id/more_minute_btn")
    if more_minute_btn.exists():
        more_minute_btn.click()
    fudai_icon = poco(type="android.widget.ImageView", name="com.xiangkan.android:id/fudai_icon")
    if fudai_icon.exists():
        fudai_icon.click()
    news_detail_layout = poco(type="android.widget.FrameLayout", name="com.xiangkan.android:id/news_detail_layout")
    if news_detail_layout.exists():
        news_detail_layout.swipe([0, -0.7], duration=1.5)
        recycler_view = news_detail_layout.offspring("androidx.recyclerview.widget.RecyclerView")
        if recycler_view.exists():
            view_group_list = recycler_view.children()
            if len(view_group_list) > 0:
                for item in view_group_list:
                    tvInfo = item.offspring("com.xiangkan.android:id/tvInfo")
                    tvInfo_ad = item.offspring("com.xiangkan.android:id/tvInfo", textMatches=".*广告.*")
                    if tvInfo.exists() and not tvInfo_ad.exists():
                        item.click()
                        break


def main():
    try:
        start()
    except Exception as e:
        print(e)


if __name__ == '__main__':
    main()
